package com.hgm.travelapp.activity

import android.content.Intent
import android.opengl.Visibility
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager
import com.google.gson.JsonObject
import com.hgm.travelapp.R
import com.hgm.travelapp.bean.UserCode
import com.hgm.travelapp.bean.UserLogin
import com.hgm.travelapp.databinding.ActivityLoginBinding
import com.hgm.travelapp.network.ApiService
import com.hgm.travelapp.network.RetrofitClient
import retrofit2.Call
import retrofit2.Response

class LoginActivity : AppCompatActivity(), View.OnClickListener {

      private var timer: CountDownTimer? = null
      private var phone: String? = null
      private var code: String? = null
      private val retrofitClient = RetrofitClient.create(ApiService::class.java)
      private var flag = false
      private val mBinding: ActivityLoginBinding by lazy {
            ActivityLoginBinding.inflate(layoutInflater)
      }

      override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            //隐藏状态栏
            requestWindowFeature(Window.FEATURE_NO_TITLE)
            window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
            setContentView(mBinding.root)
            initView()
      }

      private fun initView() {
            mBinding.apply {
                  ibBack.setOnClickListener(this@LoginActivity)
                  btnGetCode.setOnClickListener(this@LoginActivity)
                  btnLogin.setOnClickListener(this@LoginActivity)
                  swAdmin.setOnCheckedChangeListener { buttonView, isChecked ->
                        if (isChecked) {
                              mBinding.apply {
                                    tvHello.text = "管理员，您好!"
                                    etPhone.hint = "密钥账户"
                                    etCode.hint = "密码"
                                    btnGetCode.visibility = View.GONE
                                    flag = isChecked
                              }
                        } else {
                              mBinding.apply {
                                    tvHello.text = "用户，您好!"
                                    etPhone.hint = "手机号码"
                                    etCode.hint = "验证码"
                                    btnGetCode.visibility = View.VISIBLE
                                    flag = isChecked
                              }
                        }
                  }
            }
      }

      override fun onClick(v: View?) {
            when (v?.id) {
                  R.id.ib_back -> this.finish()
                  R.id.btn_getCode -> getCode()
                  R.id.btn_login -> if (flag) adminLogin() else userLogin()
            }
      }

      /**
       * 用户登录
       */
      private fun userLogin() {
            code = mBinding.etCode.text.toString().trim()
            if (TextUtils.isEmpty(code)) {
                  //显示验证码错误信息
                  mBinding.apply {
                        ivCodeError.visibility = View.VISIBLE
                        tvCodeError.visibility = View.VISIBLE
                  }
                  return
            }
            retrofitClient.userLogin(phone!!, code!!)
                  .enqueue(object : retrofit2.Callback<UserLogin> {
                        override fun onResponse(
                              call: Call<UserLogin>,
                              response: Response<UserLogin>
                        ) {
                              Log.e(
                                    "hgm",
                                    "登录成功： ${response.body().toString() ?: "response is null"}"
                              )
                              startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                        }

                        override fun onFailure(call: Call<UserLogin>, t: Throwable) {
                              Log.e("hgm", "登录失败： ${t.message}")
                        }
                  })
      }

      /**
       * 管理员登录
       */
      private fun adminLogin() {
            val name = mBinding.etPhone.text.toString().trim()
            val pwd = mBinding.etCode.text.toString().trim()
            retrofitClient.adminLogin(name, pwd).enqueue(object : retrofit2.Callback<JsonObject> {
                  override fun onResponse(call: Call<JsonObject>, response: Response<JsonObject>) {
                        Log.e("hgm", "登录成功： ${response.body().toString() ?: "response is null"}")
                        startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                  }

                  override fun onFailure(call: Call<JsonObject>, t: Throwable) {
                        Log.e("hgm", "登录失败： ${t.message}")
                  }

            })
      }


      /**
       * 获取验证码
       */
      private fun getCode() {
            phone = mBinding.etPhone.text.toString().trim()
            if (TextUtils.isEmpty(phone)) {
                  //显示手机错误信息
                  mBinding.apply {
                        ivPhoneError.visibility = View.VISIBLE
                        tvPhoneError.visibility = View.VISIBLE
                  }
                  return
            }
            countDownTimer()
            retrofitClient.getCode(phone).enqueue(object : retrofit2.Callback<UserCode> {
                  override fun onResponse(call: Call<UserCode>, response: Response<UserCode>) {
                        Log.e(
                              "hgm",
                              "验证码请求成功： ${response.body().toString() ?: "response is null"}"
                        )
                  }

                  override fun onFailure(call: Call<UserCode>, t: Throwable) {
                        Log.e("hgm", "验证码请求失败： ${t.message}")
                  }

            })
      }


      /**
       * 倒计时
       */
      private fun countDownTimer() {
            timer = object : CountDownTimer(60000, 1000) {
                  override fun onTick(millisUntilFinished: Long) {
                        var time = millisUntilFinished / 1000
                        mBinding.btnGetCode.text = "重新获取 ($time)"
                  }

                  override fun onFinish() {
                        mBinding.btnGetCode.text = "重新获取"
                  }
            }
            timer?.start()
      }


      override fun onDestroy() {
            super.onDestroy()
            timer?.cancel()
      }
}